package com.cskaoyan.market.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 小焦
 * @since 2023/03/17 14:13
 */
@WebFilter("/*")
public class CORSFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		HttpServletResponse resp = (HttpServletResponse) servletResponse;
		//允许来自于哪个域的请求发往后端 写前端的主机、端口号即可
		resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9527");
		//发往后端的请求允许何种请求方法
		resp.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
		//发送请求时允许携带的端口号
		resp.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
		//发送请求时是否允许携带cookie凭证
		resp.setHeader("Access-Control-Allow-Credentials","true");
		filterChain.doFilter(req,resp);
	}

	@Override
	public void destroy() {

	}
}
